package com.example.helloword

import android.content.Intent
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.example.helloword.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private var highScore = 0
    private var name = "王菲尔"
    private var gender = "女"
    private var phone = "2023110230"

    private val gameLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                val score = result.data?.getIntExtra("score", 0) ?: 0
                if (score > highScore) highScore = score
                updateInfo()
            }
        }

    private val editLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                val data = result.data
                name = data?.getStringExtra("name") ?: name
                gender = data?.getStringExtra("gender") ?: gender
                phone = data?.getStringExtra("phone") ?: phone
                updateInfo()
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        updateInfo()

        binding.btnEditInfo.setOnClickListener {
            val intent = Intent(this, EditInfoActivity::class.java)
            intent.putExtra("name", name)
            intent.putExtra("gender", gender)
            intent.putExtra("phone", phone)
            editLauncher.launch(intent)
        }

        binding.btnStartGame.setOnClickListener {
            val intent = Intent(this, GameActivity::class.java)
            gameLauncher.launch(intent)
        }
    }

    private fun updateInfo() {
        binding.tvInfo.text = "姓名：$name\n性别：$gender\n学号：$phone\n最高分：$highScore"
    }
}
